<template>
	<el-drawer
	  v-model="dialog.visible"
	  :title="dialog.title"
	  append-to-body
	  @close="closeDialog"
	  size="750"
	  :close-on-click-modal="false"
	>
	<el-scrollbar >
		<el-form
			ref="formRef"
			:model="formData"
			:rules="formRules"
			label-width="120px"
			label-position="top"
		>
			
			<div style="margin-bottom: 18px;">
				<span class="title-form_primary">基础信息</span>
			</div>
			
			<el-form-item prop="name">
				<el-input v-model="formData.name" placeholder="请输入接口名称" />
			</el-form-item>
			
			<el-form-item prop="code">	
				<el-input
				  v-model="formData.url"
				  placeholder="请输入请求网址"
				  class="input-with-select"
				>
				  <template #prepend>
					<Dict v-model="formData.method" code="http_method" style="width: 100px;" />
				  </template>
				</el-input>
			</el-form-item>
			
			<el-form-item prop="timeout">
			  <el-input v-model="formData.timeout" placeholder="请求超时时间" type="number" >
			    <template #append>毫秒</template>
			  </el-input>
			</el-form-item>
			
			<el-form-item label="是否启用" prop="enabled" >
				<el-radio-group v-model="formData.enabled" >
				  <el-radio value="0">禁用</el-radio>
				  <el-radio value="1">启用</el-radio>
				</el-radio-group>
			</el-form-item>
			
			<el-form-item label="默认执行" prop="defaultRunning" >
				<el-radio-group v-model="formData.defaultRunning" >
				  <el-radio value="0">手动</el-radio>
				  <el-radio value="1">自动</el-radio>
				</el-radio-group>
			</el-form-item>
			
			
			<div style="margin-bottom: 18px;">
				<span class="title-form_primary">请求头(Header)</span>
			</div>
			
			<div class="header-content">
				<el-table :data="formData.headers" border style="width: 100%">
					<el-table-column prop="name" label="参数名称" />
					<el-table-column prop="identifier" label="参数标识" width="120" />
					<el-table-column prop="required" label="参数必填" align="center" width="100">
						<template #default="scope">
						  <el-tag :type="scope.row.required == '1' ? 'danger' : 'info'">
							{{ scope.row.required == '1' ? "必填" : "可选" }}
						  </el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="defaultValue" label="参数默认值" />
					<el-table-column label="操作" width="150" fixed="right">
						<template #default="{ row, $index }">
							<el-button link type="primary" @click="handleEditHeader($index, row)">编辑</el-button>
							<el-button link type="danger" @click="removeHeader($index)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
				<div style="margin-top: 10px;">
					<el-button type="primary" @click="handleEditHeader(-1, null)">添加参数</el-button>
				</div>
			</div>
			
			<div style="margin-bottom: 18px;">
				<span class="title-form_primary">请求认证</span>
			</div>
			
			<div class="http-authentication">
				<el-form-item prop="authType">
					<Dict v-model="formData.authType" code="http_auth_type" style="width: 100%;" />
				</el-form-item>
				
				<el-form-item prop="authBearerFromRedisRead" v-if="formData.authType=='bearer_token'">
					<el-radio-group v-model="formData.authBearerFromRedisRead">
					  <el-radio :value="'0'" >常量</el-radio>
					  <el-radio :value="'1'" >缓存</el-radio>
					</el-radio-group>
				</el-form-item>
				
				<el-form-item prop="authBearerToken" v-if="formData.authType=='bearer_token' && formData.authBearerFromRedisRead=='0'">
					<el-input
					    v-model="formData.authBearerToken"
					    placeholder="Bearer ..."
					    type="textarea" />
				</el-form-item>
				
				<el-form-item prop="authBearerRedisReadKey" v-if="formData.authType=='bearer_token' && formData.authBearerFromRedisRead=='1'">
					<el-input
						v-model="formData.authBearerRedisReadKey"
						placeholder="请输入Bearer缓存Key"
						:rules="[
							{ required: true, message: '请输入Bearer缓存Key', trigger: 'blur' },
							{ min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
						]"
					/>
				</el-form-item>
				
				<el-form-item prop="basicAuthUsername" v-if="formData.authType=='basic_auth'">
					<el-input v-model="formData.basicAuthUsername" placeholder="username"  />
				</el-form-item>
				
				<el-form-item prop="basicAuthPassword" v-if="formData.authType=='basic_auth'">
					<el-input v-model="formData.basicAuthPassword" placeholder="password"  />
				</el-form-item>
				
			</div>
			
			<div style="margin-bottom: 18px;">
				<span class="title-form_primary" >请求参数</span>
			</div>
			
			<div class="http-parameter">
				<el-tabs v-model="requestParamType">
					<el-tab-pane label="Params" name="params">
						<el-table :data="formData.urlParams" border style="width: 100%">
							<el-table-column prop="name" label="参数名称" />
							<el-table-column prop="identifier" label="参数标识" width="120" />
							<el-table-column prop="required" label="参数必填" align="center" width="100">
								<template #default="scope">
								  <el-tag :type="scope.row.required == '1' ? 'danger' : 'info'">
									{{ scope.row.required == '1' ? "必填" : "可选" }}
								  </el-tag>
								</template>
							</el-table-column>
							<el-table-column prop="defaultValue" label="参数默认值" />
							<el-table-column label="操作" width="150" fixed="right">
								<template #default="{ row, $index }">
									<el-button link type="primary" @click="handleEditParam($index, row)">编辑</el-button>
									<el-button link type="danger" @click="removeParam($index)">删除</el-button>
								</template>
							</el-table-column>
						</el-table>
						<div style="margin-top: 10px;">
							<el-button type="primary" @click="handleEditParam(-1, null)">添加参数</el-button>
							</div>
					</el-tab-pane>
					<el-tab-pane label="Body" name="body">
						<el-form-item prop="bodyType">
							<div style="display: flex;flex-direction: column;justify-content: center;width: 100%;">
								<div class="body-type" style="margin-bottom: 18px;">
									<el-radio-group v-model="formData.bodyType">
										<el-radio-button value="form-data">form-data</el-radio-button>
										<el-radio-button value="x-www-form-urlencoded">x-www-form-urlencoded</el-radio-button>
										<el-radio-button value="raw-json">raw(json)</el-radio-button>
										<el-radio-button value="raw-xml">raw(xml)</el-radio-button>
							</el-radio-group>
							</div>
								
								<div class="body-form-conent" v-if="['form-data', 'x-www-form-urlencoded'].includes(formData.bodyType)">
									<el-table :data="formData.bodyParams" border style="width: 100%">
										<el-table-column prop="name" label="参数名称" />
										<el-table-column prop="identifier" label="参数标识" width="120" />
										<el-table-column prop="required" label="参数必填" align="center" width="100">
											<template #default="scope">
											  <el-tag :type="scope.row.required == '1' ? 'danger' : 'info'">
												{{ scope.row.required == '1' ? "必填" : "可选" }}
											  </el-tag>
											</template>
										</el-table-column>
										<el-table-column prop="defaultValue" label="参数默认值" />
										<el-table-column label="操作" width="150" fixed="right">
											<template #default="{ row, $index }">
												<el-button link type="primary" @click="handleEditBodyParam($index, row)">编辑</el-button>
												<el-button link type="danger" @click="removeBodyParam($index)">删除</el-button>
											</template>
										</el-table-column>
									</el-table>
									<div style="margin-top: 10px;">
										<el-button type="primary" @click="handleEditBodyParam(-1, null)">添加参数</el-button>
							</div>
							</div>

								<div class="body-raw-content" v-else>
									<div v-if="formData.bodyType === 'raw-json'" class="json-fields-manager">
										<el-table :data="jsonFields" border style="width: 100%">
											<el-table-column prop="name" label="参数名称" />
											<el-table-column prop="identifier" label="参数标识" width="120" />
											<el-table-column prop="required" label="参数必填" align="center" width="100">
												<template #default="scope">
												  <el-tag :type="scope.row.required == '1' ? 'danger' : 'info'">
													{{ scope.row.required == '1' ? "必填" : "可选" }}
												  </el-tag>
												</template>
											</el-table-column>
											<el-table-column prop="defaultValue" label="参数默认值" />
											<el-table-column label="操作" width="150" fixed="right">
												<template #default="{ row, $index }">
													<el-button link type="primary" @click="handleEditJsonField($index, row)">编辑</el-button>
													<el-button link type="danger" @click="removeJsonField($index)">删除</el-button>
												</template>
											</el-table-column>
										</el-table>
										<div style="margin-top: 10px; margin-bottom: 10px;">
											<el-button type="primary" @click="handleEditJsonField(-1, null)">添加字段</el-button>
						</div>
						</div>
									<MonacoEditor
										v-model="rawjson"
										:options="jsonEditorOptions"
										:language="formData.bodyType === 'raw-json' ? 'json' : 'xml'"
										class="editor"
										@change="handleEditorChange"
									/>
								</div>
							</div>
						</el-form-item>
					</el-tab-pane>
				</el-tabs>
			</div>
			
			<div style="margin-bottom: 18px;">
				<span class="title-form_primary" >分页请求</span>
			</div>
			
			<div class="pagination-settings">
				<el-form-item label="是否分页请求" prop="paginationType">
					<el-radio-group v-model="formData.paginationType">
						<el-radio :value="'0'">不分页</el-radio>
						<el-radio :value="'1'">请求体分页</el-radio>
						<el-radio :value="'2'">URL参数分页</el-radio>
					</el-radio-group>
				</el-form-item>
				
				<template v-if="['1','2'].includes(formData.paginationType)">
					<el-form-item label="当前页参数名" prop="pageField">
						<el-input 
							v-model="formData.pageField" 
							placeholder="请输入当前页参数名，例如：pageNum"
						>
							<template #append>
								<el-tooltip content="在请求URL或Body中使用的分页参数名" placement="top">
									<el-icon><QuestionFilled /></el-icon>
								</el-tooltip>
							</template>
						</el-input>
					</el-form-item>
					
					<el-form-item label="起始页码" prop="pageNum">
						<el-input-number 
							v-model="formData.pageNum" 
							:min="0"
							:max="1"
							placeholder="请输入起始页码"
						>
							<template #append>
								<el-tooltip content="分页起始页码，通常为0或1" placement="top">
									<el-icon><QuestionFilled /></el-icon>
								</el-tooltip>
							</template>
						</el-input-number>
					</el-form-item>
					
					<el-form-item label="每页数量参数名" prop="pageSizeField">
						<el-input 
							v-model="formData.pageSizeField" 
							placeholder="请输入每页数量参数名，例如：pageSize"
						>
							<template #append>
								<el-tooltip content="在请求URL或Body中使用的每页数量参数名" placement="top">
									<el-icon><QuestionFilled /></el-icon>
								</el-tooltip>
							</template>
						</el-input>
					</el-form-item>
					
					<el-form-item label="默认每页数量" prop="pageSize">
						<el-input-number 
							v-model="formData.pageSize" 
							:min="1" 
							:max="1000"
							placeholder="请输入默认每页数量"
						/>
					</el-form-item>
					
					<el-form-item label="请输入处理线程数量" prop="threads">
						<el-input-number 
							v-model="formData.threads" 
							:min="10" 
							:max="1000"
							placeholder="请输入处理线程数量"
						/>
					</el-form-item>
					
					<el-form-item label="总数量字段" prop="totalField">
						<el-input 
							v-model="formData.totalField" 
							placeholder="请输入总数量字段名，例如：total"
						>
							<template #append>
								<el-tooltip content="响应中包含总数量的字段路径，支持多级，如：data.total" placement="top">
									<el-icon><QuestionFilled /></el-icon>
								</el-tooltip>
							</template>
						</el-input>
					</el-form-item>
				</template>
			</div>
			
			<div style="margin-bottom: 18px;">
				<span class="title-form_primary">请求响应</span>
			</div>
			
			<div class="response-content">
				<div v-if="testResult" class="test-result">
					<div class="result-header">
						<div class="status-code">
							<span class="label">状态码：</span>
							<el-tag :type="getStatusCodeType(testResult.statusCode)">
								{{ testResult.statusCode }}
							</el-tag>
						</div>
					</div>

					<el-tabs v-model="responseTab">
						<el-tab-pane label="响应体" name="body">
							<div class="response-body">
								<div class="response-toolbar">
									<el-radio-group v-model="responseFormat" size="small">
										<el-radio-button value="json">JSON</el-radio-button>
										<el-radio-button value="xml">XML</el-radio-button>
										<el-radio-button value="text">Text</el-radio-button>
									</el-radio-group>
								</div>
								<div class="response-content-wrapper">
									<MonacoEditor
										v-if="testResult && responseContent"
										:key="responseContent"
										v-model="responseContent"
										:language="responseFormat === 'xml' ? 'text' : responseFormat"
										:options="monacoOptions"
										class="response-editor"
									/>
									<div v-else-if="testResult" class="empty-response">
										<el-empty description="无响应内容" />
									</div>
								</div>
							</div>
						</el-tab-pane>
						<el-tab-pane label="响应头" name="headers">
							<div class="headers-list">
								<div v-for="(header, index) in testResult.headers" :key="index" class="header-item">
									<span class="header-name">{{ header.name }}:</span>
									<span class="header-value">{{ header.value }}</span>
								</div>
							</div>
						</el-tab-pane>
					</el-tabs>
				</div>
			</div>
		</el-form>
		</el-scrollbar>
		<template #footer>
		  <div class="dialog-footer">
			<el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
			<el-button 
			  type="success" 
			  @click="handleTest" 
			  :loading="loading" 
			  :disabled="!formData.id"
			>测 试</el-button>
			<el-button @click="closeDialog" :loading="loading">取 消</el-button>
		  </div>
		</template>
	</el-drawer>
	<EditParamFieldDrawer
		ref="paramFieldDrawerRef"
		@success="handleParamFieldSuccess"
		@closed="handleParamFieldClosed"
		@parse-fields="handleParseJsonFields"
	/>
</template>

<script lang="ts" setup>
	
	import HttpAPI from "@/api/biz/http";
	import type {FormRules } from 'element-plus'
	import MonacoEditor from '@/components/MonacoEditor/index.vue'
	import EditParamFieldDrawer from '@/components/DataWorkflow/components/EditParamFieldDrawer.vue';
	

	// 1. 基础响应式变量
	const loading = ref(false);
	const dialog = ref({
		visible: false,
		title: '',
	});
	const formRef = ref();
	const requestParamType = ref('params');
	const responseTab = ref('body');
	const responseFormat = ref<'json' | 'xml' | 'text'>('json');
	const responseContent = ref('');
	const testResult = ref<any>(null);

	const paramFieldDrawerRef = ref();
	const currentEditType = ref(''); // header, param, body
	const currentEditIndex = ref(-1);
	const jsonFields = ref<any[]>([]);

	// 2. 常量定义
	const DEFAULT_TIMEOUT = 5000;
	const DEFAULT_METHOD = 'GET';
	const DEFAULT_AUTH_TYPE = 'none';
	const DEFAULT_BODY_TYPE = 'form-data';

	// 3. 编辑器配置
	const monacoOptions = {
		readOnly: true,
		theme: 'vs-dark',
		minimap: { enabled: false },
		scrollBeyondLastLine: false,
		automaticLayout: true
	};

	const jsonEditorOptions = {
		theme: 'vs-dark',
		automaticLayout: true,
		formatOnPaste: true,
		formatOnType: true,
		minimap: { enabled: false },
		scrollBeyondLastLine: false,
		tabSize: 2,
		fontSize: 14,
		language: 'json',
	};

	// 4. 表单数据
	const formData = ref<any>({
		method: DEFAULT_METHOD,
		timeout: DEFAULT_TIMEOUT,
		enabled:'0',
		defaultRunning:'0',
		threads:10,
		authType: DEFAULT_AUTH_TYPE,
		authBearerToken: '',
		authBearerFromRedisRead:'0',
		authBearerRedisReadKey:"",
		basicAuthUsername: '',
		basicAuthPassword: '',
		headers: [],
		urlParams: [],
		bodyType: DEFAULT_BODY_TYPE,
		bodyParams: [],
		rawContent: '',
		paginationType: '0',
		pageField: 'pageNum',
		pageSizeField: 'pageSize',
		pageSize: 10,
		pageNum: 1,
		totalField: 'total',
		requestParamType: 'params',
	});

	// 5. 监听器
	watch([() => responseFormat.value, () => testResult.value], () => {
		if (!testResult.value?.body) {
			responseContent.value = '';
			return; 
		}

		const content = testResult.value.body;
		
		try {
			switch (responseFormat.value) {
				case 'json':
					try {
						const obj = JSON.parse(content);
						responseContent.value = JSON.stringify(obj, null, 2);
					} catch {
						responseContent.value = content;
					}
					break;
				case 'xml':
					if (content.trim().startsWith('<?xml') || content.trim().startsWith('<')) {
						responseContent.value = content
							.replace(/></g, '>\n<')
							.replace(/(<\/?[^>]+>)/g, '$1\n')
							.split('\n')
							.filter((line:any) => line.trim())
							.map((line:any) => {
								const match = line.match(/^\s*/);
								const indentLength = match ? match[0].length : 0;
								return '  '.repeat(indentLength / 2) + line.trim();
							})
							.join('\n');
					} else {
						responseContent.value = content;
					}
					break;
				default:
					responseContent.value = content;
			}
		} catch (e) {
			console.warn('格式化响应内容失败:', e);
			responseContent.value = content;
		}
	}, { immediate: true });

	// 添加类型定义
	interface FormData {
		[key: string]: any;  // 添加索引签名
		id?: string;
		name?: string;
		url?: string;
		method: string;
		timeout: number;
		enabled:'0' | '1';
		defaultRunning:'0' | '1';
		threads:10,
		authType: string;
		authBearerToken: string;
		authBearerFromRedisRead:'0' | '1';
		authBearerRedisReadKey:string;
		basicAuthUsername: string;
		basicAuthPassword: string;
		headers: Array<{
			key: string;
			value: string;
			remark: string;
			type: 'string' | 'number' | 'boolean' | 'date';
			source: 'fixed' | 'redis' | 'sql' | 'http';
		}>;
		urlParams: Array<{
			key: string;
			value: string;
			remark: string;
		}>;
		bodyType: string;
		bodyParams: Array<{
			key: string;
			value: string;
			remark: string;
		}>;
		rawContent: string;
		paginationType: '0' | '1';
		pageField: string;
		pageSizeField: string;
		pageSize: number;
		pageNum: number;
		totalField: string;
		requestParamType: string;
	}

	// 获取状态码对应的标签类型
	const getStatusCodeType = (code: any) => {
		const map: Record<any, any> = {
				'200': 'success',
				'300': 'warning',
				'400': 'danger',
				'500': 'error',
				'normal': 'info'
		 };
		if (code >= 200 && code < 300)  return map['200'] 
		if (code >= 300 && code < 400) return map['300'] 
		if (code >= 400 && code < 500) return map['400'] 
		if (code >= 500) return map['500'] 
		return map['normal'] ;
	};
	
	// 提取公共的验证规则
	const createAuthValidator = (authType: string, fieldName: string) => {
		return (_rule: any, value: string, callback: Function) => {
			if (formData.value.authType === authType && !value) {
				callback(new Error(`${fieldName}不能为空`));
			} else {
				callback();
			}
		};
	};

	// 优化验证规则定义
	const formRules = reactive<FormRules>({
		name: [
			{ required: true, message: '请输入接口名称', trigger: 'blur' },
			{ min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
		],
		url: [
			{ required: true, message: '请输入请求网址', trigger: 'blur' },
			{ min: 2, max: 500, message: '长度在 2 到 500 个字符', trigger: 'blur' }
		],
		method: [{ required: true, message: "请求方法不能为空", trigger: "change" }],
		timeout: [{ required: true, message: "超时时间不能为空", trigger: "blur" }],
		authType: [{ required: true, message: "认证类型不能为空", trigger: "change" }],
		authBearerToken: [{ 
			required: true, 
			message: "Bearer Token不能为空", 
			trigger: "blur",
			validator: createAuthValidator('bearer_token', 'Bearer Token')
		}],
		authBearerFromRedisRead: [{
			required: true, 
			message: "Bearer Token获取方式不能为空", 
			trigger: "blur",
			validator: createAuthValidator('authBearerFromRedisRead', 'Bearer Token Read')
		}],
		authBearerRedisReadKey: [
			{ 
				required: true, 
				message: '请输入Bearer缓存Key', 
				trigger: 'blur',
				validator: (_rule: any, value: string) => {
					if (formData.value.authType === 'bearer_token' && 
						formData.value.authBearerFromRedisRead === '1' && 
						(!value || value.trim() === '')) {
						return new Error('请输入Bearer缓存Key');
					}
					return true;
				}
			},
			{ min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
		],
		basicAuthUsername: [{ 
			required: true, 
			message: "用户名不能为空", 
			trigger: "blur",
			validator: createAuthValidator('basic_auth', '用户名')
		}],
		basicAuthPassword: [{ 
			required: true, 
			message: "密码不能为空", 
			trigger: "blur",
			validator: createAuthValidator('basic_auth', '密码')
		}],
		bodyType: [{ required: true, message: "请求体类型不能为空", trigger: "change" }],
		rawContent: [{
			required: true,
			message: "请求体内容不能为空",
			trigger: "blur",
			validator: (_rule:any, value:any, callback:any) => {
				if (['raw-json', 'raw-xml'].includes(formData.value.bodyType)) {
					if (!value) {
						callback(new Error('请求体内容不能为空'))
					} else if (formData.value.bodyType === 'raw-json') {
						try {
							JSON.parse(value)
							callback()
						} catch (e) {
							callback(new Error('JSON 格式不正确'))
						}
					} else {
						callback()
					}
				} else {
					callback()
				}
			}
		}],
		paginationType: [{ required: true, message: "请选择是否分页请求", trigger: "change" }],
		totalField: [{ required: true, message: "请输入数据量取值字段", trigger: "change" }],
		threads: [{ required: true, message: "请输入处理线程数量", trigger: "change" }],
		pageField: [
			{ 
				required: true, 
				message: '请输入当前页参数名', 
				trigger: 'blur',
				validator: (_rule: any, value: string) => {
					if (formData.value.paginationType === '1' && (!value || value.trim() === '')) {
						return new Error('请输入当前页参数名');
					}
					return true;
				}
			}
		],
		pageSizeField: [
			{
				required: true,
				message: '请输入每页数量参数名',
				trigger: 'blur',
				validator: (_rule: any, value: string) => {
					if (formData.value.paginationType === '1' && (!value || value.trim() === '')) {
						return new Error('请输入每页数量参数名');
					}
					return true;
				}
			}
		],
		pageSize: [
			{
				required: true,
				message: '请输入默认每页数量',
				trigger: 'blur',
				validator: (_rule: any, value: number) => {
					if (formData.value.paginationType === '1' && (!value || value < 1)) {
						return new Error('请输入有效的默认每页数量');
					}
					return true;
				}
			}
		],
		pageNum: [
			{
				required: true,
				message: '请输入起始页码',
				trigger: 'blur',
				validator: (_rule: any, value: number) => {
					if (formData.value.paginationType === '1' && (value === undefined || value < 0)) {
						return new Error('请输入有效的起始页码');
					}
					return true;
				}
			}
		],
	});
	
	async function openDialog(row?: any, type?: string) {
		resetForm();
		console.log('row data:', row); // 添加日志
		
		dialog.value = {
			visible: true,
			title: type === 'add' ? '新增HTTP数据源' : '编辑HTTP数据源'
		};

		if (type === 'add') {
			formData.value = {
				method: DEFAULT_METHOD,
				timeout: DEFAULT_TIMEOUT,
				authType: DEFAULT_AUTH_TYPE,
				enabled:'0',
				defaultRunning:'0',
				threads:10,
				authBearerToken: '',
				authBearerFromRedisRead:'0' ,
				authBearerRedisReadKey:'',
				basicAuthUsername: '',
				basicAuthPassword: '',
				bodyType: DEFAULT_BODY_TYPE,
				headers: [],
				urlParams: [],
				bodyParams: [],
				rawContent: '',
				id: undefined,
				name: undefined,
				url: undefined,
				paginationType: '0',
				pageField: 'pageNum',
				pageSizeField: 'pageSize',
				pageSize: 10,
				pageNum: 1,
				totalField: 'total',
				requestParamType: 'params',
			};
			return;
		}

		try {
			console.log(row);
			// 基础数据，显式声明类型
			const baseData: FormData = {
				id: row.id,
				name: row.name,
				url: row.url,
				method: row.method || DEFAULT_METHOD,
				timeout: row.timeout || DEFAULT_TIMEOUT,
				enabled:row.enabled || '0',
				defaultRunning:row.defaultRunning || '0',
				threads:row.threads || 10,
				authType: row.authType || DEFAULT_AUTH_TYPE,
				authBearerToken: row.authBearerToken || '',
				authBearerFromRedisRead:row.authBearerFromRedisRead || '0',
				authBearerRedisReadKey:row.authBearerRedisReadKey || '',
				basicAuthUsername: row.basicAuthUsername || '',
				basicAuthPassword: row.basicAuthPassword || '',
				bodyType: row.bodyType || DEFAULT_BODY_TYPE,
				rawContent: row.rawContent || '',
				headers: [],
				urlParams: [],
				bodyParams: [],
				paginationType: row.paginationType || '0',
				pageField: row.pageField || 'pageNum',
				pageSizeField: row.pageSizeField || 'pageSize',
				pageSize: row.pageSize || 10,
				pageNum: row.pageNum ?? 1,
				totalField: row.totalField,
				requestParamType: row.requestParamType || 'params',
			};
			
			requestParamType.value=row.requestParamType || 'params'

			// 解析数组类型的字段
			try {
				baseData.headers = row.headers ? JSON.parse(row.headers) : [];
			} catch (e) {
				console.warn('解析 headers 失败:', e);
				baseData.headers = [];
			}

			try {
				baseData.urlParams = row.urlParams ? JSON.parse(row.urlParams) : [];
			} catch (e) {
				console.warn('解析 params 失败:', e);
				baseData.urlParams = [];
			}

			try {
				baseData.bodyParams = row.bodyParams ? JSON.parse(row.bodyParams) : [];
			} catch (e) {
				console.warn('解析 bodyParams 失败:', e);
				baseData.bodyParams = [];
			}
			
			try {
				if(baseData.bodyType === 'raw-json'){
					jsonFields.value=row.rawContent ? JSON.parse(row.rawContent) : [];
					updateJsonContent();
		}else{
					rawjson.value=row.rawContent;
				}
			} catch (e) {
				console.warn('解析 rawContent 失败:', e);
				jsonFields.value = [];
			}

			formData.value = {
				...baseData,
				pageSize: row.pageSize || 10,
				pageNum: row.pageNum ?? 1,
				requestParamType: row.requestParamType || 'params',
			};
			console.log('parsed formData:', formData.value); // 添加日志
			requestParamType.value = formData.value.requestParamType;
		} catch (e) {
			console.error('加载数据失败:', e);
			ElMessage.error('加载数据失败');
			closeDialog();
		}
	}
	
	const rawjson=ref();
	
	const submitForm = () => {
		formRef.value.validate((isValid: boolean) => {
		  if (isValid) {
			   loading.value = true;
				
				// 构建保存数据
				const saveData = {
					id: formData.value.id,
					name: formData.value.name,
					url: formData.value.url,
					method: formData.value.method,
					timeout: formData.value.timeout,
					enabled:formData.value.enabled,
					defaultRunning:formData.value.defaultRunning,
					threads:formData.value.threads,
					
					// 认证信息
					authType: formData.value.authType,
					authBearerToken: formData.value.authBearerToken,
					basicAuthUsername: formData.value.basicAuthUsername,
					basicAuthPassword: formData.value.basicAuthPassword,
					
					// 请求头和参数
					headers: JSON.stringify(formData.value.headers),
					urlParams: JSON.stringify(formData.value.urlParams),
					
					// 请求体相关
					bodyType: formData.value.bodyType,
					bodyParams: JSON.stringify(formData.value.bodyParams),
					rawContent: formData.value.rawContent,
					requestParamType: requestParamType.value,
					
					//分页信息
					paginationType: formData.value.paginationType ,
					pageField: formData.value.pageField,
					pageSizeField: formData.value.pageSizeField ,
					pageSize: formData.value.pageSize ,
					pageNum: formData.value.pageNum ,
					totalField: formData.value.totalField,
				};
				
				if(formData.value.bodyType=='raw-json'){
					saveData.rawContent=JSON.stringify(jsonFields.value, null, 2);
				}
				// 调用保存接口
				HttpAPI.save(saveData)
				.then(() => {
						ElMessage.success("保存成功");
						closeDialog();
					})
					.catch((error:any) => {
						console.error('保存失败:', error);
						ElMessage.error(error.message || "保存失败");
					})
					.finally(() => {
						loading.value = false;
					});
			} else {
				ElMessage.warning("请填写必填项");
			}
		});
	};
	
	const emits = defineEmits(['closeDialog'])
	const closeDialog=()=>{
		dialog.value.visible=false;
		dialog.value.title="";
		emits('closeDialog',formData)
		resetForm();
	}
	
	/**
	 * 重置表单
	 */
	function resetForm() {
		// 重置表单验证
		formRef.value?.resetFields();
		formRef.value?.clearValidate();

		// 重置表单数据
		formData.value = {
			// 基础信息
			id: undefined,
			name: undefined,
			url: undefined,
			method: DEFAULT_METHOD,
			timeout: DEFAULT_TIMEOUT,
			enabled:'0',
			defaultRunning:'0',		
			threads:10,
			// 认证信息
			authType: DEFAULT_AUTH_TYPE,
			authBearerToken: '',
			authBearerFromRedisRead:'0',
			authBearerRedisReadKey:'',
			basicAuthUsername: '',
			basicAuthPassword: '',
			
			// 请求头和参数
			headers: [],
			urlParams: [],
			
			// 请求体相关
			bodyType: DEFAULT_BODY_TYPE,
			bodyParams: [],
			rawContent: '',
			paginationType: '0',
			pageField: 'pageNum',
			pageSizeField: 'pageSize',
			pageSize: 10,
			pageNum: 1,
			totalField: 'total',
			requestParamType: 'params',
		};
		// 重置标签页
		requestParamType.value = 'params';
		testResult.value = null;
		responseFormat.value = 'json';
		responseTab.value = 'body';
		jsonFields.value=[];
	}	
	
	const removeHeader = (index: number) => formData.value.headers.splice(index, 1);
	const removeParam = (index: number) => formData.value.urlParams.splice(index, 1);
	const removeBodyParam = (index: number) => formData.value.bodyParams.splice(index, 1);
	
	// 处理编辑器内容变化
	const handleEditorChange = (value: string) => {
		if (formData.value.bodyType === 'raw-json') {
			try {
				// 尝试解析 JSON
				JSON.parse(value)
				// 清除验证错误
				formRef.value?.clearValidate('rawContent')
			} catch (e) {
				// JSON 格式错误，显示验证错误
				formRef.value?.validateField('rawContent')
			}
		} else if (formData.value.bodyType === 'raw-xml') {
			// 可以添加 XML 格式验证逻辑
			if (value.trim()) {
				formRef.value?.clearValidate('rawContent')
			}
		}
	}
	
	// 修改测试方法
	const handleTest = () => {
		if (!formData.value?.id) {
			ElMessage.warning('请先保存接口后再进行测试');
			return;
		}

		loading.value = true;
		testResult.value = null; // 清空之前的测试结果
		responseContent.value = ''; // 清空之前的响应内容

		HttpAPI.test(formData.value.id)
			.then((result:any) => {
				console.log('测试结果:', result); // 添加日志
				testResult.value = result;
				responseTab.value = 'body';
				
				// 设置响应内容
				const content = result.body || '';
				
				// 自动检测响应格式
				const contentType = result.headers.find((h:any) => 
					h.name.toLowerCase() === 'content-type'
				)?.value?.toLowerCase() || '';

				if (contentType.includes('application/json')) {
					responseFormat.value = 'json';
					try {
						const obj = JSON.parse(content);
						responseContent.value = JSON.stringify(obj, null, 2);
					} catch {
						responseContent.value = content;
					}
				} else if (contentType.includes('application/xml') || contentType.includes('text/xml')) {
					responseFormat.value = 'xml';
					responseContent.value = formatXML(content);
				} else {
					responseFormat.value = 'text';
					responseContent.value = content;
				}
			})
			.catch((error:any) => {
				console.error('测试失败:', error); // 添加错误日志
				ElMessage.error(error.message || '测试失败');
				testResult.value = null;
				responseContent.value = '';
			})
			.finally(() => {
				loading.value = false;
			});
	};

	// 添加 XML 格式化函数
	const formatXML = (xml: string) => {
		if (!xml.trim().startsWith('<')) return xml;
		
		try {
			return xml
				.replace(/></g, '>\n<')
				.replace(/(<\/?[^>]+>)/g, '$1\n')
				.split('\n')
				.filter(line => line.trim())
				.map(line => {
					const match = line.match(/^\s*/);
					const indentLevel = match ? match[0].length : 0;
					return '  '.repeat(indentLevel / 2) + line.trim();
				})
				.join('\n');
		} catch {
			return xml;
		}
	};
	
	// 打开参数编辑抽屉
	const openParamFieldDrawer = (type: string, index: number, row?: any) => {
		currentEditType.value = type;
		currentEditIndex.value = index;
		paramFieldDrawerRef.value?.openDialog(index, row, row ? 'edit' : 'add');
	};

	// 处理参数编辑成功
	const handleParamFieldSuccess = (index: number, data: any) => {
		
		console.log(index,"=",data);
		
		switch (currentEditType.value) {
			case 'header':
				if (index === -1) {
					formData.value.headers.push(data);
				} else {
					formData.value.headers[index] = data;
				}
				break;
			case 'param':
				if (index === -1) {
					formData.value.urlParams.push(data);
				} else {
					formData.value.urlParams[index] = data;
				}
				break;
			case 'body':
				if (index === -1) {
					formData.value.bodyParams.push(data);
				} else {
					formData.value.bodyParams[index] = data;
				}
				break;
				
			case 'json':
				if (index === -1) {
					jsonFields.value.push(data);
				} else {
					jsonFields.value[index] = data;
				}
				updateJsonContent();
				break;	
		}
	};
	// 处理参数编辑关闭
	const handleParamFieldClosed = () => {
		currentEditType.value = '';
		currentEditIndex.value = -1;
	};

	// 修改原有的编辑方法
	const handleEditHeader = (index: number, row: any) => {
		openParamFieldDrawer('header', index, row);
	};

	// 添加编辑参数方法
	const handleEditParam = (index: number, row: any) => {
		openParamFieldDrawer('param', index, row);
	};

	// 添加编辑方法
	const handleEditBodyParam = (index: number, row: any) => {
		openParamFieldDrawer('body', index, row);
	};

	// 添加JSON字段管理方法
	const handleEditJsonField = (index: number, row: any) => {
		openParamFieldDrawer('json', index, row);
	};

	const removeJsonField = (index: number) => {
		jsonFields.value.splice(index, 1);
		updateJsonContent();
	};

	// 处理解析出的JSON字段
	const handleParseJsonFields = (fields: any[]) => {
		switch (currentEditType.value) {
			case 'header':
				const headerPaths = new Set(formData.value.headers.map(f => f.key));
				const newHeaderFields = fields.filter(f => !headerPaths.has(f.key));
				if (newHeaderFields.length === 0) {
					ElMessage.warning('没有新的字段需要添加');
					break;
				}
				formData.value.headers.push(...newHeaderFields);
				ElMessage.success(`成功添加 ${newHeaderFields.length} 个字段`);
				break;
			case 'param':
				const paramPaths = new Set(formData.value.urlParams.map(f => f.key));
				const newParamFields = fields.filter(f => !paramPaths.has(f.key));
				if (newParamFields.length === 0) {
					ElMessage.warning('没有新的字段需要添加');
					break;
				}
				formData.value.urlParams.push(...newParamFields);
				ElMessage.success(`成功添加 ${newParamFields.length} 个字段`);
				break;
			case 'body':
				const bodyPaths = new Set(formData.value.bodyParams.map(f => f.key));
				const newBodyFields = fields.filter(f => !bodyPaths.has(f.key));
				if (newBodyFields.length === 0) {
					ElMessage.warning('没有新的字段需要添加');
					break;
				}
				formData.value.bodyParams.push(...newBodyFields);
				ElMessage.success(`成功添加 ${newBodyFields.length} 个字段`);
				break;
			case 'json':
				const jsonPaths = new Set(jsonFields.value.map(f => f.key));
				const jsonBodyFields = fields.filter(f => !jsonPaths.has(f.key));
				if (jsonBodyFields.length === 0) {
					ElMessage.warning('没有新的字段需要添加');
					updateJsonContent();
					break;
				}
				jsonFields.value.push(...jsonBodyFields);
				ElMessage.success(`成功添加 ${jsonBodyFields.length} 个字段`);
				updateJsonContent();
				break;
		}
	};
	
	const updateJsonContent = () => {
		try {
			const jsonObj: Record<string, any> = {};
			jsonFields.value.forEach(field => {
				let current = jsonObj;
				const paths = field.identifier.split('.');
				paths.forEach((path: string, index: number) => {
					if (index === paths.length - 1) {
						current[path] = field.defaultValue;
					} else {
						current[path] = current[path] || {};
						current = current[path];
					}
				});
			});
			rawjson.value=JSON.stringify(jsonObj, null, 2);
		} catch (error) {
			console.error('更新JSON内容失败:', error);
		}
	};
	
	defineExpose({
	  openDialog,closeDialog
	});
	
	onMounted(() => {
	});
</script>

<style scoped>
	.title-form_primary {
		font-style: normal;
		font-weight: 500;
		font-size: 14px;
		color: #1f2329;
		position: relative;
		padding-left: 5px;
	}
	
	.title-form_primary:before {
	    content: "";
	    width: 2px;
	    height: 14px;
	    background: var(--el-color-primary);
	    position: absolute;
	    top: 50%;
	    transform: translateY(-50%);
	    left: 0;
	}
	
	.row-content {
		display: flex;
		flex-direction: row;
		align-items: flex-start;
		margin-bottom: 10px;
		gap: 5px;
		
		:deep(.el-select) {
			width: 120px;
		}
	}
	
	.body-raw-content {
		margin-top: 8px;
		width: 100%;
		display: flex;
		flex-direction: column;
		flex: 1;
	}

	.editor {
		height: 400px;
		min-height: 250px;
		width: 100%;
		border: 1px solid var(--el-border-color);
		border-radius: 4px;
		flex: 1;
		min-width: 0;
		overflow: hidden;
	}

	.el-form-item {
		width: 100%;
	}

	.el-form-item__content {
		width: 100%;
	}

	.response-content {
		border: 1px solid var(--el-border-color);
		border-radius: 4px;
		overflow: hidden;
	}

	.test-result {
		.result-header {
			padding: 12px;
			display: flex;
			justify-content: space-between;
		align-items: center;
			border-bottom: 1px solid var(--el-border-color);
			
			.status-code {
				display: flex;
				align-items: center;
				gap: 8px;
				
				.label {
					font-weight: 500;
				}
			}
		}
		
		.response-editor {
			max-height: 400px;
			border: none;
		}
		
		.headers-list {
			padding: 12px;
			
			.header-item {
				padding: 4px 0;
				display: flex;
				gap: 8px;
				
				.header-name {
					color: var(--el-text-color-secondary);
					min-width: 120px;
				}
				
				.header-value {
					color: var(--el-text-color-primary);
					word-break: break-all;
				}
			}
		}
	}

	.response-body {
		position: relative;
		height: 300px;
		display: flex;
		flex-direction: column;
	}

	.response-toolbar {
		padding: 8px;
		border-bottom: 1px solid var(--el-border-color);
	}

	.response-content-wrapper {
		flex: 1;
		position: relative;
		overflow: hidden;
	}

	.empty-response {
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: var(--el-fill-color-light);
	}

	.response-editor {
		height: 100%;
		width: 100%;
		overflow: hidden;
	}

	.pagination-settings {
		padding: 16px;
		background-color: var(--el-fill-color-light);
		border-radius: 4px;
		margin-bottom: 18px;
	}
	
	.pagination-settings :deep(.el-form-item:last-child) {
		margin-bottom: 0;
	}
</style>